using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using ctsu.Admin.Forms.CoreLab;

using Syncfusion.Windows.Forms.Grid;
using Syncfusion.Windows.Forms.Tools;
using ctsu.Admin.Forms;
using ctsu.BaseForms;
using ctsu.Security;
using ctsu.Shared;
using ctsu.Data;

namespace ctsu.Admin.BusLogic.CoreLab
{
	public class BLFormNewFromExistingIn : BLCoreLabFormBaseImpl
	{
		private SelectLocationDlg _sld;
		//private bool ignoreEvent = false;
		private ArrayList _alExistIDs;

		#region control references
		private TextBox _id;
		private DateTimePickerAdv _batchInDate;

		private ComboBox _testType;
		private ComboBox _unitOfMeasure;

		private TextBox _smallNote;
		private TextBox _note;

		private ComboBox _freezer;
		private NumericUpDown _shelf;
		private NumericUpDown _rack;
		private NumericUpDown _box;

		private Button _btnNewTest;
		private Button _btnNewUnit;
		private Button _btnRetrieveItems;
		private Button _btnClear;
		private Button _btnEditBatch;
		private Button _btnRemoveBatch;
		private Button _btnPrint;
		private Button _btnGrid;
		private Button _selectLocation;

		private CheckBox _chkGridTracking;
		private CheckBox _chkShowPatient;
		//private CheckBox _chkIncludeComment;		
		private CheckBox _chkPrintLabels;
		#endregion control references

		#region initialize
		public BLFormNewFromExistingIn(FormMain formMain, FormBase form, FormInfoBase formInfo, DataTable tableSchema, Permission formSecurity, Hashtable configData)
			: base(formMain, form, formInfo, tableSchema, formSecurity, configData)
		{
		}

		protected override void _vcManager_OnAfterHookEvents()
		{
			_id = (TextBox)Forms.Utils.GetControlByName("ID", this._form.Controls);
			_batchInDate = (DateTimePickerAdv)Forms.Utils.GetControlByName("BatchInDate", this._form.Controls);

			_testType = (ComboBox)Forms.Utils.GetControlByName("TestType", this._form.Controls);
			_unitOfMeasure = (ComboBox)Forms.Utils.GetControlByName("UnitOfMeasure", this._form.Controls);
			_smallNote = (TextBox)Forms.Utils.GetControlByName("SmallNote", this._form.Controls);
			_note = (TextBox)Forms.Utils.GetControlByName("Note", this._form.Controls);

			_freezer = (ComboBox)Forms.Utils.GetControlByName("Freezer", this._form.Controls);
			_shelf = (NumericUpDown)Forms.Utils.GetControlByName("Shelf", this._form.Controls);
			_rack = (NumericUpDown)Forms.Utils.GetControlByName("Rack", this._form.Controls);
			_box = (NumericUpDown)Forms.Utils.GetControlByName("Box", this._form.Controls);

			_btnNewTest = (Button)Forms.Utils.GetControlByName("btnNewTest", this._form.Controls);
			_btnNewUnit = (Button)Forms.Utils.GetControlByName("btnNewUnit", this._form.Controls);
			_selectLocation = (Button)Forms.Utils.GetControlByName("SelectLocation", this._form.Controls);

			_btnRetrieveItems = (Button)Forms.Utils.GetControlByName("btnRetrieveItems", this._form.Controls);
			_btnClear = (Button)Forms.Utils.GetControlByName("btnClear", this._form.Controls);
			_btnRemoveBatch = (Button)Forms.Utils.GetControlByName("btnRemoveBatch", this._form.Controls);
			_btnEditBatch = (Button)Forms.Utils.GetControlByName("btnEditBatch", this._form.Controls);
			_btnGrid = (Button)Forms.Utils.GetControlByName("btnGrid", this._form.Controls);
			_btnPrint = (Button)Forms.Utils.GetControlByName("btnPrint", this._form.Controls);
			_chkPrintLabels = (CheckBox)Forms.Utils.GetControlByName("chkPrintLabels", this._form.Controls);
			_chkPrintReport = (CheckBox)Forms.Utils.GetControlByName("chkPrintReport", this._form.Controls);
			_chkPerPatient = (CheckBox)Forms.Utils.GetControlByName("chkPerPatient", this._form.Controls);
			_chkPrintSelected = (CheckBox)Forms.Utils.GetControlByName("chkPrintSelected", this._form.Controls);
			_chkShowPatient = (CheckBox)Forms.Utils.GetControlByName("chkShowPatient", this._form.Controls);
			_chkGridTracking = (CheckBox)Forms.Utils.GetControlByName("chkGridTracking", this._form.Controls);
			this._form.btnRemove.Visible = false;
			this._form.btnEdit.Visible = false;
			this._form.btnSearch.Visible = false;
			_chkGridTracking.Visible = false;
			_btnGrid.Visible = false;
		}

		public override void InitializeEmptyControls()
		{
			base.InitializeEmptyControls();
			_testType.SelectedIndex = -1;
			_testType.SelectedIndex = -1;
			_unitOfMeasure.SelectedIndex = -1;
			_unitOfMeasure.SelectedIndex = -1;
			_freezer.SelectedIndex = -1;
		}

		protected override void SetControlsEnabled(bool enable)
		{
			base.SetControlsEnabled(enable);
			_btnClear.Enabled = enable;
			_btnRetrieveItems.Enabled = enable;
			_btnNewTest.Enabled = enable;
			_btnNewUnit.Enabled = enable;
			_selectLocation.Enabled = enable;

			if (enable == false)
			{
				_btnEditBatch.Enabled = enable;
				_btnRemoveBatch.Enabled = enable;
			}

			_testType.SelectedIndex = -1;
			_testType.SelectedIndex = -1;
			_testType.Enabled = enable;

			_unitOfMeasure.SelectedIndex = -1;
			_unitOfMeasure.SelectedIndex = -1;
			_unitOfMeasure.Enabled = enable;

			_smallNote.Enabled = enable;
			_smallNote.Text = "";
			_note.Enabled = enable;
			_note.Text = "";
			_chkShowPatient.Enabled = enable;

			_freezer.Enabled = enable;
			_freezer.SelectedIndex = -1;
			_freezer.SelectedIndex = -1;
			_shelf.Enabled = enable;
			_shelf.Value = 0;
			_rack.Enabled = enable;
			_rack.Value = 0;
			_box.Enabled = enable;
			_box.Value = 0;
		}
		#endregion initialize

		public override void GenericClick(Control sender)
		{
			if (sender.Name == "btnRetrieveItems")
				SelectSamples();
			if (sender.Name == "btnEditBatch")
				EditBatch();
			if (sender.Name == "btnRemoveBatch")
				RemoveBatch();
			if (sender.Name == "btnClear")
				ClearInfo();
			if (sender.Name == "btnPrint")
				DoPrint();
			if (sender.Name == "btnNewTest")
				NewTest();
			if (sender.Name == "btnNewUnit")
				NewUnit();
			if (sender.Name == "SelectLocation")
				SelectLocation();
		}

		#region new combo items
		private void NewTest()
		{
			StringBuilder sb = new StringBuilder();

			string sql = "SELECT Display " +
				" FROM TestType_L " +
				" WHERE 1=2";

			DataTable tableSchema;
			try
			{
				tableSchema = Forms.Utils.GetTableSchema(null, sql);
				NewListRecordDlg nd = new NewListRecordDlg("Display", "TestType_L", tableSchema);
				nd.ShowDialog(this._form);

				Forms.Utils.LoadCbo(_testType, "TestType_L", true);
				_testType.SelectedValue = nd.NewID;

				//reset the grid column comboBox
				BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["TestSamples"];
				GridControl grid = fgbl.Grid;

				GridStyleInfo gsi = grid.ColStyles[3];
				SpecialLookup sl = (SpecialLookup)this._formInfo.SpecialLookups["TestType"];
				Forms.Utils.LoadCbo(sl, gsi);
			}
			catch (Exception ex)
			{
				//bool b = //ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Error encountered while retrieving table schema for TestType.");
				sb.Append(Environment.NewLine);
				sb.Append("Error: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
		}

		private void NewUnit()
		{
			StringBuilder sb = new StringBuilder();

			string sql = "SELECT Display " +
				" FROM UnitOfMeasure_L " +
				" WHERE 1=2";

			DataTable tableSchema;
			try
			{
				tableSchema = Forms.Utils.GetTableSchema(null, sql);
				NewListRecordDlg nd = new NewListRecordDlg("Display", "UnitOfMeasure_L", tableSchema);
				nd.ShowDialog(this._form);

				Forms.Utils.LoadCbo(_unitOfMeasure, "UnitOfMeasure_L", true);
				_unitOfMeasure.SelectedValue = nd.NewID;

				//reset the grid column comboBox
				BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["TestSamples"];
				GridControl grid = fgbl.Grid;

				GridStyleInfo gsi = grid.ColStyles[4];
				SpecialLookup sl = (SpecialLookup)this._formInfo.SpecialLookups["UnitOfMeasure"];
				Forms.Utils.LoadCbo(sl, gsi);
			}
			catch (Exception ex)
			{
				//bool b = //ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Error encountered while retrieving table schema for UnitOfMeasure.");
				sb.Append(Environment.NewLine);
				sb.Append("Error: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
		}
		#endregion new
		#region select location
		public override void Cancel()
		{
			if (_sld != null)
				_sld.Close();
			base.Cancel();
		}

		private void SelectLocation()
		{
			_selectLocation.Enabled = false;
			int protocol = 0;
			string test = "";
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);
			GridRangeInfoList list;

			list = grid.Selections.GetSelectedRows(true, false);
			if (list.Count > 0)
			{
				GridRangeInfo range = list[0];
				int row = range.Top;

				protocol = (int)grid[row, 4].CellValue;
				test = grid[row, 6].FormattedText;
				//				if(test.Length == 0)
				//				{
				//					MessageBox.Show("Select a test");
				//
				//				}

			}

			_sld = new SelectLocationDlg(test, protocol, grid, this._form.Text);
			_sld.Owner = this._form;
			_sld.SelectLocationEvent += new SelectLocationDlg.SelectLocationEventHandler(sld_SelectLocationEvent);
			_sld.Closing += new CancelEventHandler(sld_Closing);
			_sld.Show();
		}

		private void sld_SelectLocationEvent(object sender, SelectLocationEventArgs e)
		{
			DisplayLocationInControls(e.Location);
		}

		private void sld_Closing(object sender, CancelEventArgs e)
		{
			SelectLocationDlg sld = (SelectLocationDlg)sender;
			sld.SelectLocationEvent -= new SelectLocationDlg.SelectLocationEventHandler(sld_SelectLocationEvent);
			sld.Closing -= new CancelEventHandler(sld_Closing);
			if (this._formMode == EditMode.Edit || this._formMode == EditMode.New)
				this._selectLocation.Enabled = true;
			_sld = null;
		}

		#endregion select location
		public override void New()
		{
			this._alExistIDs = new ArrayList();
			base.New();
		}


		public override bool Save()
		{
			bool b = base.Save();
			//display the existing id data
			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["TestSamples"];
			GridControl grid = fgbl.Grid;
			for (int i = 1; i < grid.RowCount + 1; i++)
			{
				grid[i, 2].CellValue = (int)this._alExistIDs[i - 1];
			}
			return b;
		}


		private void RemoveFromList(int origID)
		{
			foreach (int i in _alExistIDs)
			{
				if (i == origID)
				{
					_alExistIDs.Remove(i);
					break;
				}
			}
		}

		#region select samples
		private void SelectSamples()
		{
			SampleChooserDlg dlc = new SampleChooserDlg();
			dlc.Owner = this._form;
			dlc.Text = "Select Samples";
			dlc.SelectSampleClick += new ctsu.Admin.Forms.CoreLab.SampleChooserDlg.SelectSampleButtonClickEventHandler(dlc_SelectSampleClick);
			dlc.Show();
		}

		private void dlc_SelectSampleClick(object sender, SelectSamplesEventArgs e)
		{
			if (e.SelectType == 0)
				RetrieveSampleBatch(e.ID);
			else
				RetrieveOneSample(e.ID, true);

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["TestSamples"];
			GridControl grid = fgbl.Grid;
			if (grid.RowCount > 0)
			{
				if (!this._btnEditBatch.Enabled)
				{
					this._btnEditBatch.Enabled = true;
					this._btnRemoveBatch.Enabled = true;
					this._form.btnSave.Enabled = true;
				}
			}
		}

		private void RetrieveOneSample(int id, bool displayMessage)
		{
			StringBuilder sb = new StringBuilder();

			if (IsInList(id))
			{
				if (displayMessage)
				{
					sb.Append("Sample ID: " + id + " is already in the list");
					MessageBox.Show(this._form, sb.ToString(), "Duplicate ID",
						MessageBoxButtons.OK, MessageBoxIcon.Information);
				}
				return;
			}

			string sql = "SELECT t.ID, t.DrawSample, " +
				" d.Protocol, d.Patient, d.Visit, d.VisitDate, d.VisitTime, s.Display " +
				" FROM TestSamples t INNER JOIN DrawSamples d ON d.ID=t.DrawSample " +
				" INNER JOIN SampleType_L s ON s.ID=d.SampleType " +
				" WHERE t.ID =" + id;


			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["TestSamples"];
			GridControl grid = fgbl.Grid;

			//SqlConnection conn = LoginForm.GetSqlConnection();			
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);

				Sample samp = null;
				string message = "";

				grid.BeginUpdate();
				if (reader.Read())
				{
					Cursor.Current = Cursors.WaitCursor;
					samp = new Sample();
					samp.Tag = reader.GetInt32(0);
					samp.DrawID = reader.GetInt32(1);
					samp.Protocol = reader.GetInt32(2);
					//get protocolInfo
					samp.ProtocolInfo = CoreLabUtils.GetProtocolInfo(samp.Protocol, out message);

					samp.PatientID = reader.GetInt32(3);
					//get the patient info
					samp.PatientInfo = CoreLabUtils.GetPatientInfo(samp.PatientID, out message);
					samp.Visit = reader.GetString(4);
					samp.VisitDate = reader.GetDateTime(5);
					samp.VisitTime = reader.GetString(6);
					samp.SampleName = reader.GetString(7);
					fgbl.AddRow(samp, 0);
					_alExistIDs.Add(samp.Tag);
				}
				else
				{
					sb.Append("Sample ID: " + id + " could not be found");
					MessageBox.Show(this._form, sb.ToString(), "Sample Not Found",
						MessageBoxButtons.OK, MessageBoxIcon.Information);
					reader.Close();
					return;
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve sample!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = //ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Get Sample Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				grid.EndUpdate();
			}
		}

		private void RetrieveSampleBatch(int num)
		{
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT t.ID, t.DrawSample, " +
				" d.Protocol, d.Patient, d.Visit, d.VisitDate, d.VisitTime, s.Display " +
				" FROM TestSamples t INNER JOIN DrawSamples d ON d.ID=t.DrawSample " +
				" INNER JOIN SampleType_L s ON s.ID=d.SampleType " +
				" WHERE t.BatchInNum =" + num +
				" ORDER BY t.ID";

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["TestSamples"];
			GridControl grid = fgbl.Grid;

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);
				Sample samp = null;
				string message = "";

				if (reader.Read())
				{
					Cursor.Current = Cursors.WaitCursor;
					grid.BeginUpdate();
					do
					{
						samp = new Sample();
						samp.BatchInNum = num;
						samp.Tag = reader.GetInt32(0);
						if (IsInList((int)samp.Tag))
							continue;
						samp.DrawID = reader.GetInt32(1);
						samp.Protocol = reader.GetInt32(2);
						//get protocolInfo
						samp.ProtocolInfo = CoreLabUtils.GetProtocolInfo(samp.Protocol, out message);

						samp.PatientID = reader.GetInt32(3);
						//get the patient info
						samp.PatientInfo = CoreLabUtils.GetPatientInfo(samp.PatientID, out message);
						samp.Visit = reader.GetString(4);
						samp.VisitDate = reader.GetDateTime(5);
						samp.VisitTime = reader.GetString(6);
						samp.SampleName = reader.GetString(7);
						fgbl.AddRow(samp, 0);
						_alExistIDs.Add(samp.Tag);
					}
					while (reader.Read());
				}
				else
				{
					sb.Append("Batch was not found.");
					MessageBox.Show(this._form, sb.ToString(), "Draw Not Found",
						MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve batch!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = //ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Retrieve Batch Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				grid.EndUpdate();
			}
		}

		private bool IsInList(int id)
		{
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);
			GridStyleInfo gsi = null;

			if (grid.RowCount == 0)
				return false;

			for (int i = 1; i <= grid.RowCount; i++)
			{
				gsi = grid[i, 1];
				if (gsi.Text.Length > 0)
					if (Convert.ToInt32(gsi.CellValue) == id)
						return true;
			}
			return false;
		}
		#endregion select samples

		#region clear and display from grid
		private void ClearInfo()
		{
			this._testType.SelectedIndex = -1;
			this._testType.SelectedIndex = -1;
			this._unitOfMeasure.SelectedIndex = -1;
			this._unitOfMeasure.SelectedIndex = -1;
			this._smallNote.Text = "";
			this._note.Text = "";
		}

		protected override void grd_CellDoubleClick(object sender, GridCellClickEventArgs e)
		{
			if (e.RowIndex < 1)
				return;
			if (this.FormMode == EditMode.Edit || this.FormMode == EditMode.New)
				FillControlsWithRowData(e.RowIndex);
		}

		private void FillControlsWithRowData(int row)
		{
			GridControl grid = ((BLCoreLabFormGridBaseImpl)this._gridBLs["TestSamples"]).Grid;
			//location			
			string sVal = grid[row, 8].Text;
			DisplayLocationInControls(sVal);

			this._testType.SelectedIndex = (int)grid[row, 6].CellValue;
			this._unitOfMeasure.SelectedIndex = (int)grid[row, 7].CellValue;
			this._smallNote.Text = grid[row, 9].Text;
			this._note.Text = grid[row, 10].Text;
		}

		private void DisplayLocationInControls(string location)
		{
			if (location.Length == 0)
			{
				ClearLocation();
				return;
			}

			string[] a = location.Split(',');
			foreach (string s in a)
			{
				if (s.StartsWith("Fz"))
				{
					this._freezer.SelectedValue = Convert.ToInt32(s.Substring(3));
				}
				if (s.StartsWith("Sf"))
				{
					this._shelf.Value = Convert.ToInt32(s.Substring(3));
				}
				if (s.StartsWith("Rk"))
				{
					this._rack.Value = Convert.ToInt32(s.Substring(3));
				}
				if (s.StartsWith("Bx"))
				{
					this._box.Value = Convert.ToInt32(s.Substring(3));
				}
			}
		}
		private void ClearLocation()
		{
			this._freezer.SelectedIndex = -1;
			this._freezer.SelectedIndex = -1;
			this._shelf.Value = 0;
			this._rack.Value = 0;
			this._box.Value = 0;
		}
		#endregion clear and display from grid

		#region update remove data
		private void EditBatch()
		{
			this._btnEditBatch.Enabled = false;
			NewFromExistingInEditDlg ebd = new NewFromExistingInEditDlg(this);

			ebd.ButtonClick += new ctsu.Admin.Forms.CoreLab.NewFromExistingInEditDlg.ButtonClickEventHandler(ebd_ButtonClick);
			ebd.Closing += new CancelEventHandler(ebd_Closing);
			ebd.Owner = this._form;
			ebd.Show();
		}

		private void ebd_ButtonClick(object sender, EditBatchEventArgs e)
		{
			if (e.ButtonName == "ReplaceSelected")
				EditReplaceSelected(e.ReplaceColumns, e.ColumnMatch);
			if (e.ButtonName == "ReplaceAll")
				EditReplaceAll(e.ReplaceColumns, e.ColumnMatch);
		}

		private void ebd_Closing(object sender, CancelEventArgs e)
		{
			NewFromExistingInEditDlg ebd = (NewFromExistingInEditDlg)sender;
			ebd.ButtonClick -= new NewFromExistingInEditDlg.ButtonClickEventHandler(ebd_ButtonClick);
			ebd.Closing -= new CancelEventHandler(ebd_Closing);
			if (this._formMode == EditMode.Edit || this._formMode == EditMode.New)
				this._btnEditBatch.Enabled = true;
		}

		private void RemoveBatch()
		{
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);

			GridRangeInfoList list;
			list = grid.Selections.GetSelectedRows(true, false);
			if (list.Count == 0)
				return;

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)this._gridBLs["TestSamples"];

			ArrayList alRows = new ArrayList();
			int row = 0;
			int top = 0;
			int bottom = 0;
			for (int i = 0; i < list.Count; i++)
			{
				top = list[i].Top;
				bottom = list[i].Bottom;
				if (bottom > top)
					GetSelectedRows(alRows, top, bottom);
				else
					alRows.Add(list[i].Top);
			}
			for (int i = 0; i < alRows.Count; i++)
			{
				row = (int)alRows[i];
				row -= i;
				DataRow dr = (DataRow)fgbl.Grid[row, 0].Tag;
				dr.RejectChanges();
				fgbl.RemoveRow(row);
			}
		}

		private void GetSelectedRows(ArrayList alRows, int top, int bottom)
		{
			int rows = bottom - top + 1;
			for (int i = 0; i < rows; i++)
				alRows.Add(top + i);
		}

		private void EditReplaceAll(bool[] replaceColumns, Hashtable columnMatch)
		{
			Sample samp = new Sample();
			samp.TestType = -2;
			samp.UnitOfMeasure = -2;

			if (!SetReplacementColumns(replaceColumns, ref samp))
				return;

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)this._gridBLs["TestSamples"];

			for (int i = 1; i <= fgbl.Grid.RowCount; i++)
				fgbl.ReplaceRow(samp, i);

			this._form.btnSave.Enabled = true;
		}


		private void EditReplaceSelected(bool[] replaceColumns, Hashtable columnMatch)
		{
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);

			GridRangeInfoList list;
			list = grid.Selections.GetSelectedRows(true, false);

			Sample samp = new Sample();
			samp.TestType = -2;
			samp.UnitOfMeasure = -2;

			if (!SetReplacementColumns(replaceColumns, ref samp))
				return;

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)this._gridBLs["TestSamples"];

			foreach (GridRangeInfo range in list)
			{
				for (int i = range.Top; i <= range.Bottom; i++)
				{
					fgbl.ReplaceRow(samp, i);
					this._form.btnSave.Enabled = true;
				}
			}
		}

		private bool SetReplacementColumns(bool[] replaceColumns, ref Sample samp)
		{
			StringBuilder sb = new StringBuilder();
			if (replaceColumns[0])
			{
				if (!VerifyAllColumns())
					return false;
				samp.TestType = (int)this._testType.SelectedValue;
				samp.UnitOfMeasure = (int)this._unitOfMeasure.SelectedValue;

				if (this._smallNote.Text.Length == 0)
					samp.SmallNote = " ";
				else
					samp.SmallNote = this._smallNote.Text;

				if (this._note.Text.Length == 0)
					samp.Note = " ";
				else
					samp.Note = this._note.Text;

				samp.Location = GetFormatatedLocation();
			}
			if (replaceColumns[1])
			{
				if (this._testType.Text.Length == 0)
				{
					sb.Append("You must enter the test type!");
					MessageBox.Show(this._form, sb.ToString(), "Test Type", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_testType.Focus();
					return false;
				}
				samp.TestType = (int)this._testType.SelectedValue;
			}
			if (replaceColumns[2])
			{
				if (this._unitOfMeasure.Text.Length == 0)
				{
					sb.Append("You must enter the unit of measure!");
					MessageBox.Show(this._form, sb.ToString(), "Unit Of Measure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_unitOfMeasure.Focus();
					return false;
				}
				samp.UnitOfMeasure = (int)this._unitOfMeasure.SelectedValue;
			}
			if (replaceColumns[3])
			{
				if (_smallNote.Text.Length == 0)
				{
					sb.Append("Are you sure you want to replace the label note with a blank entry!");
					if (MessageBox.Show(this._form, sb.ToString(), "Result", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
					{
						_smallNote.Focus();
						return false;
					}
					else
						samp.SmallNote = " ";
				}
				else
					samp.SmallNote = _smallNote.Text;
			}
			if (replaceColumns[4])
			{
				if (_note.Text.Length == 0)
				{
					sb.Append("Are you sure you want to replace the comment column with a blank entry!");
					if (MessageBox.Show(this._form, sb.ToString(), "Comment", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
					{
						_note.Focus();
						return false;
					}
					else
						samp.Note = " ";
				}
				else
					samp.Note = _note.Text;
			}
			if (replaceColumns[5])
			{
				if (!VerifyLocation())
				{
					MessageBox.Show(this._form, "The location is invalid.", "Invalid Location", MessageBoxButtons.OK, MessageBoxIcon.Stop);
					return false;
				}
				samp.Location = GetFormatatedLocation();
			}
			return true;
		}

		private bool VerifyAllColumns()
		{
			StringBuilder sb = new StringBuilder();
			if (!VerifyLocation())
			{
				MessageBox.Show(this._form, "The location is invalid.", "Invalid Location", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return false;
			}
			if (this._testType.Text.Length == 0)
			{
				sb.Append("You must enter the test type!");
				MessageBox.Show(this._form, sb.ToString(), "Test Type", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				_testType.Focus();
				return false;
			}
			if (this._unitOfMeasure.Text.Length == 0)
			{
				sb.Append("You must enter the unit of measure!");
				MessageBox.Show(this._form, sb.ToString(), "Unit Of Measure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				_unitOfMeasure.Focus();
				return false;
			}

			if (_smallNote.Text.Length == 0)
			{
				sb.Append("Are you sure you want to replace label note with a blank entry!");
				if (MessageBox.Show(this._form, sb.ToString(), "Comment", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
				{
					_smallNote.Focus();
					return false;
				}
			}

			if (_note.Text.Length == 0)
			{
				sb.Append("Are you sure you want to replace comment with a blank entry!");
				if (MessageBox.Show(this._form, sb.ToString(), "Comment", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
				{
					_note.Focus();
					return false;
				}
			}
			return true;
		}
		private bool VerifyLocation()
		{
			if (this._freezer.SelectedIndex == -1)
				return false;
			if (this._shelf.Value == 0)
				return false;
			if (this._shelf.Value > 9)
				return false;
			if (this._rack.Value > 9)
				return false;
			if (this._box.Value == 0)
				return false;
			return true;
		}

		private string GetFormatatedLocation()
		{
			if (_freezer.SelectedIndex == -1)
				return "";

			string location = "Fz:" + this._freezer.SelectedValue.ToString() + "," +
				"Sf:" + this._shelf.Value.ToString() + "," +
				"Rk:" + this._rack.Value.ToString() + "," +
				"Bx:" + this._box.Value.ToString();
			return location;
		}
		#endregion update remove data

		#region print
		private void DoPrint()
		{
			if (!HasRows())
			{
				StringBuilder sb = new StringBuilder();
				sb.Append("There are no labels to print.");
				sb.Append(Environment.NewLine);
				MessageBox.Show(this._form, sb.ToString(), "No Labels", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}
			if (HasRowNoID())
			{
				StringBuilder sb = new StringBuilder();
				sb.Append("You must press save to give the new labels an ID.");
				sb.Append(Environment.NewLine);
				MessageBox.Show(this._form, sb.ToString(), "No Label ID", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}

			if (_chkPrintLabels.Checked)
				PrintLabels();

			if (_chkPrintReport.Checked)
				PrintReport(0);
		}


		private void _pDoc_PrintPage(object sender, PrintPageEventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			Graphics gfx = e.Graphics;
			float pageBottom = gfx.VisibleClipBounds.Height;
			float pageWidth = gfx.VisibleClipBounds.Width;
			float leftMargin = 50;
			float topMargin = 50;

			Font prntFont = new Font("Arial", 10);
			Font titleFont = new Font("Arial", 14, FontStyle.Bold);
			Font subTitleFont = new Font("Arial", 12);
			Font ColumnHeadFont = new Font("Arial", 10, FontStyle.Bold);

			Pen pen = new Pen(Color.Black);

			//get the line height with some padding
			float lineHeight = prntFont.GetHeight(e.Graphics) + 2;

			//set the drawing to the top left of the page
			float yPos = topMargin;
			float xPos = leftMargin;

			//print page #
			string page = "Page " + this._page;
			PrintingUtils.PrintCenter(page, e, prntFont, pageBottom - lineHeight);

			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);
			string batchDate = ((Syncfusion.Windows.Forms.Tools.DateTimePickerAdv)Forms.Utils.GetControlByName("BatchInDate", this._form.Controls)).Value.ToShortDateString();

			//print title and subtitle
			if (this._page == 1)
			{
				PrintingUtils.PrintCenter("Core Lab - Test Labels Report", e, titleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics) + 2;

				sb.Append("Batch #: " + _sBatch);
				sb.Append("   Batch Date: " + batchDate);
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			else
			{
				sb.Append("Test Labels Report - Batch #: " + _sBatch + " continued");
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			yPos += lineHeight;

			//print heading
			float c1 = 25; //+65
			float c2 = 90; //+60
			float c3 = 150; //+60
			float c4 = 210; //+60			
			float c5 = 285; //175
			float c6 = 460; //100			
			float c7 = 560; //100
			float c8 = 660; //50			
			float c9 = 710; //70			
			float c10 = 780; //80
			float c11 = 860; //50
			float c12 = 910; //100

			float c1W = 65; //id
			float c2W = 60;  //orig id
			float c3W = 60;  //draw id
			float c4W = 60;  //spid
			float c5W = 175; //patient 
			float c6W = 100; //sample
			float c7W = 100; //test			
			float c8W = 50; //unit
			float c9W = 70; //visit
			float c10W = 80; //date
			float c11W = 50; //time
			float c12W = 100; //location

			RectangleF rec = new RectangleF();

			gfx.DrawRectangle(Pens.Black, 23, yPos, (pageWidth - 48), lineHeight);
			gfx.FillRectangle(Brushes.LightBlue, 23, yPos, pageWidth - 48, lineHeight);

			PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, c1W);
			gfx.DrawString("Test ID", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c2, yPos, lineHeight, c2W);
			gfx.DrawString("Orig ID", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c3, yPos, lineHeight, c3W);
			gfx.DrawString("Draw ID", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c4, yPos, lineHeight, c4W);
			gfx.DrawString("SPID", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c5, yPos, lineHeight, c5W);
			gfx.DrawString("Patient", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c6, yPos, lineHeight, c6W);
			gfx.DrawString("Sample Type", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c7, yPos, lineHeight, c7W);
			gfx.DrawString("Test Type", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c8, yPos, lineHeight, c8W);
			gfx.DrawString("Unit", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c9, yPos, lineHeight, c9W);
			gfx.DrawString("Visit", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c10, yPos, lineHeight, c10W);
			gfx.DrawString("Date", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c11, yPos, lineHeight, c11W);
			gfx.DrawString("Time", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c12, yPos, lineHeight, c12W);
			gfx.DrawString("Location", ColumnHeadFont, Brushes.Black, rec);
			yPos += lineHeight;

			lineHeight = prntFont.GetHeight(e.Graphics) + 18;
			//get the number of lines we can print
			int maxLines = (int)Math.Ceiling((double)((pageBottom - yPos) / lineHeight));
			maxLines -= 2;
			int curLine = 0;

			StringFormat fmt = new StringFormat();
			fmt.Trimming = StringTrimming.EllipsisCharacter;

			float yDraw;
			int iVal = 0;
			string sVal = "";
			Sample samp = null;
			DateTime dtVal = new DateTime(0);

			GridRangeInfoList list = grid.Selections.GetSelectedRows(true, false);
			for (int i = _startRange; i < list.Count; i++)
			{
				GridRangeInfo range = (GridRangeInfo)list[i];
				for (int row = range.Top; row <= range.Bottom; row++)
				{
					if (row < _startRow)
						row = _startRow;

					if (curLine == maxLines)
					{
						_startRow = row;
						_startRange = i;
						this._page++;
						e.HasMorePages = true;
						return;
					}

					yDraw = yPos + 5;
					//test id
					iVal = (int)grid[row, 1].CellValue;
					PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, c1W);
					gfx.DrawString(iVal.ToString("0000"), prntFont, Brushes.Black, rec, fmt);

					//orig id
					PrintingUtils.SetRectangle(ref rec, c2, yDraw, lineHeight, c2W);
					iVal = (int)grid[row, 2].CellValue;
					gfx.DrawString(iVal.ToString("0000"), prntFont, Brushes.Black, rec);

					//draw id
					PrintingUtils.SetRectangle(ref rec, c3, yDraw, lineHeight, c3W);
					iVal = (int)grid[row, 3].CellValue;
					gfx.DrawString(iVal.ToString("0000"), prntFont, Brushes.Black, rec);

					samp = (Sample)grid[row, 1].Tag;

					//spid
					//PrintingUtils.SetRectangle(ref rec, c4, yPos, lineHeight, c4W);
					//gfx.DrawString(samp.ProtocolInfo.SPID.ToString(), prntFont, Brushes.Black, rec);

					//patient					
					PrintingUtils.SetRectangle(ref rec, c5, yPos, lineHeight, c5W);
					if (samp.PatientInfo.Name.Length > 0)
						sVal = samp.PatientInfo.Name + "/" + samp.PatientInfo.GetMrnOrOtherIdentifier();
					else
						sVal = samp.PatientInfo.GetMrnOrOtherIdentifier();
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					//sample
					PrintingUtils.SetRectangle(ref rec, c6, yPos, lineHeight, c6W);
					gfx.DrawString(samp.SampleName, prntFont, Brushes.Black, rec, fmt);

					//test
					PrintingUtils.SetRectangle(ref rec, c7, yPos, lineHeight, c7W);
					sVal = grid[row, 6].FormattedText;
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					//units
					PrintingUtils.SetRectangle(ref rec, c8, yPos, lineHeight, c8W);
					sVal = grid[row, 7].FormattedText;
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					PrintingUtils.SetRectangle(ref rec, c9, yPos, lineHeight, c9W);
					gfx.DrawString(samp.Visit, prntFont, Brushes.Black, rec, fmt);

					PrintingUtils.SetRectangle(ref rec, c10, yPos, lineHeight, c10W);
					gfx.DrawString(samp.VisitDate.ToShortDateString(), prntFont, Brushes.Black, rec, fmt);

					PrintingUtils.SetRectangle(ref rec, c11, yPos, lineHeight, c11W);
					gfx.DrawString(samp.VisitTime, prntFont, Brushes.Black, rec, fmt);

					PrintingUtils.SetRectangle(ref rec, c12, yPos, lineHeight, c12W);
					sVal = grid[row, 8].Text;
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);


					gfx.DrawRectangle(Pens.Black, 23, yPos, (pageWidth - 48), lineHeight);
					yPos += lineHeight;
					curLine++;
				}
			}
		}

		private void PrintReport(int type)
		{
			StringBuilder sb = new StringBuilder();
			string formatFile = System.Windows.Forms.Application.StartupPath + "\\Bartender\\" + CremaConstants.LabelReportFormatFile;

			this._pDoc = new PrintDocument();
			this._pDoc.DefaultPageSettings.Landscape = true;
			this._pDlg = new PrintDialog();
			this._pDlg.Document = this._pDoc;

			if (this._pDlg.ShowDialog(this._form) == DialogResult.Cancel)
				return;

			bool doClear = false;
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);

			Cursor.Current = Cursors.WaitCursor;
			if (type == 0)
				this._pDoc.PrintPage += new PrintPageEventHandler(_pDoc_PrintPage);


			_sBatch = this._currentPrimaryID.ToString();
			try
			{
				System.Windows.Forms.Application.DoEvents();
				//				_btApp = new BarTender.ApplicationClass();							
				//				BarTender.Format btFmt = _btApp.Formats.Open(formatFile, true, "");

				_page = 1;
				_startRow = 1;
				_startRange = 0;

				if (this._chkPrintSelected.Checked)
				{
					if (grid.Selections.Count == 0)
					{
						sb.Append("Select rows to print or uncheck the 'Print Select Rows' check box.");
						MessageBox.Show(this._form, sb.ToString(), "No Rows Selected", MessageBoxButtons.OK, MessageBoxIcon.Stop);
						return;
					}
					else
					{
						//get the start row								
						GridRangeInfoList list = grid.Selections.GetSelectedRows(true, false);
						GridRangeInfo range = (GridRangeInfo)list[0];
						_startRow = range.Top;
					}
				}
				else
				{
					grid.Selections.Add(GridRangeInfo.Rows(1, grid.RowCount));
					doClear = true;
				}

				this._pDoc.Print();
			}
			catch (Exception ex)
			{
				//bool b = //ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not start bartender server");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Bartender Server Failed To Start", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				//				if(_btApp != null)
				//				{
				//					_btApp.Quit(BarTender.BtSaveOptions.btDoNotSaveChanges);
				//					_btApp = null;
				//				}				
				if (type == 0)
					this._pDoc.PrintPage -= new PrintPageEventHandler(_pDoc_PrintPage);
				if (doClear)
					grid.Selections.Clear();
			}
		}

		private void PrintLabels()
		{
			string message = "";
			StringBuilder sb = new StringBuilder();
			string fileName = System.Windows.Forms.Application.LocalUserAppDataPath + "\\" + CremaConstants.TestLabelsFileName;
			string formatFile = System.Windows.Forms.Application.StartupPath + "\\Bartender\\" + CremaConstants.TestLabelsFormatFile;

			Cursor.Current = Cursors.WaitCursor;
			if (CreateTextFile(out message))
			{
				try
				{
                    //System.Windows.Forms.Application.DoEvents();
                    //_btApp = new BarTender.ApplicationClass();
                    //_btApp.LicenseServer.Connect();
                    //if (!_btApp.LicenseServer.IsConnected)
                    //{
                    //    Exception exx = new Exception("Unable to connect to bartender server.");
                    //    ExceptionPolicy.HandleException(exx, "Exception Policy");

                    //    sb.Append("Unable to connect to the label server.");
                    //    sb.Append(Environment.NewLine);
                    //    sb.Append("You are not able to print labels at this time.  Please try again later.");
                    //    MessageBox.Show(this._form, sb.ToString(), "Server Not Connected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    //    return;
                    //}

					//check which printer to use
					string computerName = System.Net.Dns.GetHostName().ToUpper();
					string printer = "";
					switch (computerName)
					{
						case "PVTWXPG30203":
							printer = @"\\arctic\end07zlb01";
							break;
						case "PVTWXPG34207":
							printer = @"\\arctic\end07zlb01";
							break;
						case "PVTWXPG28306":
							printer = @"\\arctic\end07zlb01";
							break;
						case "R09870":
							printer = @"\\arctic\end07zlb01";
							break;
						case "PVTWXPG35325":
							printer = @"\\arctic\pav06zlb01";
							break;
						case "PVTWXPG":
							printer = @"\\arctic\far08zlb09";
							break;
					}

                    //BarTender.Format btFmt = _btApp.Formats.Open(formatFile, true, printer);

                    //IEnumerator ien = btFmt.Databases.GetEnumerator();
                    //while (ien.MoveNext())
                    //{
                    //    BarTender.Database btDb = (BarTender.Database)ien.Current;
                    //    btDb.TextFile.FileName = fileName;
                    //}

                    //btFmt.PrintOut(true, true);
				}
				catch (Exception ex)
				{
					//ExceptionPolicy.HandleException(ex, "Exception Policy");
					sb.Append("You must have the bar code program, 'Bartender', installed on your computer.");
					sb.Append(Environment.NewLine);
					sb.Append("If Bartender is insatlled then a connection to Bartender server could not be made.");
					MessageBox.Show(this._form, sb.ToString(), "Bartender Server Failed To Start", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				finally
				{
                    //if (_btApp != null)
                    //{
                    //    //_btApp.Quit(BarTender.BtSaveOptions.btDoNotSaveChanges);
                    //    //_btApp = null;
                    //}
				}
			}
			else
			{
				sb.Append("Could not create text file template for Bartender Server.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + message);
				MessageBox.Show(this._form, sb.ToString(), "Bartender Server Create Text File Template Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private bool CreateTextFile(out string message)
		{
			message = "";
			StreamWriter sw = null;
			string fileName = System.Windows.Forms.Application.LocalUserAppDataPath + "\\" + CremaConstants.TestLabelsFileName;

			bool doClear = false;
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);
			StringBuilder sb = new StringBuilder();

			string test = "";
			int len = 0;
			try
			{
				int iVal = 0;
				string sVal = "";
				Sample samp = null;
				DateTime dtVal = new DateTime(0);
				sw = new StreamWriter(fileName, false);

				if (this._chkPrintSelected.Checked)
				{
					if (grid.Selections.Count == 0)
					{
						sb.Append("Select rows to print or uncheck the 'Print Select Rows' check box.");
						MessageBox.Show(this._form, sb.ToString(), "No Rows Selected", MessageBoxButtons.OK, MessageBoxIcon.Stop);
						return false;
					}
				}
				else
				{
					grid.Selections.Add(GridRangeInfo.Rows(1, grid.RowCount));
					doClear = true;
				}

				//write header
				sw.WriteLine(CremaConstants.TestSampleHeader);

				GridRangeInfoList list = grid.Selections.GetSelectedRows(true, false);
				for (int i = 0; i < list.Count; i++)
				{
					GridRangeInfo range = (GridRangeInfo)list[i];
					for (int row = range.Top; row <= range.Bottom; row++)
					{
						sb = new StringBuilder();
						//test label ID
						iVal = (int)grid[row, 1].CellValue;
						sb.Append(iVal.ToString("0000") + "~");

						//draw label ID				 
						iVal = (int)grid[row, 3].CellValue;
						sb.Append(iVal.ToString("0000") + "~");

						samp = (Sample)grid[row, 1].Tag;

						//patient																				
						if (_chkShowPatient.Checked)
						{
							if (samp.PatientInfo.Name.Length > 0)
								sVal = samp.PatientInfo.Name + "/" + samp.PatientInfo.GetMrnOrOtherIdentifier();
							else
								sVal = samp.PatientInfo.GetMrnOrOtherIdentifier();
						}
						else
							sVal = samp.PatientInfo.GetMrnOrOtherIdentifier();
						sb.Append(sVal + "~");

						//spid						
						//sb.Append(samp.ProtocolInfo.SPID.ToString() + "~");

						//sample						
						sb.Append(samp.SampleName + "~");

						//test
						sVal = grid[row, 6].FormattedText;
						len = sVal.Length;
						if (len > 15)
							sVal = sVal.Substring(0, 14);
						test = sVal;

						//units
						sVal = grid[row, 7].FormattedText;
						if (sVal != "NA")
							test += " " + sVal;
						sb.Append(test + "~");

						sb.Append(samp.Visit + "~");

						sb.Append(samp.VisitTime + "~");

						sb.Append(samp.VisitDate.ToShortDateString() + "~");

						//note
						sVal = grid[row, 9].Text;
						sb.Append(sVal + "~");
						sw.WriteLine(sb.ToString());
					}
				}
			}
			catch (Exception ex)
			{
				//bool b = //ExceptionPolicy.HandleException(ex, "Exception Policy");
				message = ex.Message;
				return false;
			}
			finally
			{
				if (sw != null)
					sw.Close();
				if (doClear)
					grid.Selections.Clear();
			}
			return true;
		}
		#endregion print
	}
}
